
<?php
/**
 * 牌局日志备份和缓存实日志
 * Created by PhpStorm.
 * Keter
 * 2016/8/1
 * @守护进程
 */
class SavePaijuBackLogHandler extends ScriptBase
{
    /**
     * 游戏服保存的牌局日志KEY
     */
    const LOG_NAME = 'cardLogBackup';

    /**
     * 出错备份
     */
    const QUEEN_BACKUP_NAME = 'cardLogBackupErr2';

    /**
     * 当前脚本暂停标志
     * 同类结果为TRUE时则暂停和停止，如1
     */
    const SUSPEND_TAG = 'PAIJU_LOG_HANDLER_SUSPEND'; //暂停

    /**
     * 停止脚本标志
     */
    const STOP_TAG = 'PAIJU_LOG_HANDLER_STOP'; //停止

    /**
     * PHP用牌局日志缓存KEY
     */
    const CACHE_KEY = 'PJL';

    /**
     * 读取数据处理条数  add by tmac
     */
    const CACHE_LIMIT_NUMBER = 1000;

    /**
     * 日志文件大小  add by tmac
     */
    const LOG_FILE_SIZE = 254000000;
    /**
     * 过期时间
     */
    private $_expireTime;

    /**
     * 牌局日志Redis
     */
    protected $paijuRedis;

    /**
     * 逻辑代码
     */
    public function logic()
    {
        set_time_limit(0);

        $this->setExpireTime();

        // 连接redis
        $this->paijuRedis = $this->redis('paiju_log');
        $lenth = $this->paijuRedis->lLen( self::LOG_NAME );

        for($i=0; $i<= $lenth; $i++ ){
//                    $element = $this->paijuRedis->lrange( self::LOG_NAME, -1, -1 );
//                    $result      = $this->logHandler($element);
//                    $lastElement =  $this->paijuRedis->rpop(self::LOG_NAME);
            $lastElement =  $this->paijuRedis->rpop(self::LOG_NAME);
            if($lastElement){
                //$this->paijuRedis->lpush(self::QUEEN_BACKUP_NAME, $lastElement);
                $result = $lastElement ?  $this->logHandler($lastElement) : true;
                // 如果没有处理成功，则放入备份队列
                if ( !$result ) {
                    echo '--11---';
                    $this->paijuRedis->lpush(self::QUEEN_BACKUP_NAME, $lastElement);
                }
            }
        }
        $this->deinitRedis('paiju_log');
    }

    /**
     * 设置过期时间
     */
    public function setExpireTime()
    {
        if (isset(GlobalConfig::$redis_expire['paiju_log'])
            && GlobalConfig::$redis_expire['paiju_log']
        ) {
            $expireDay = (integer)GlobalConfig::$redis_expire['paiju_log'];
        } else {
            $expireDay = 5;
        }

        $this->_expireTime = 86400 * $expireDay;
    }

    /**
     * 执行脚本
     * @param $redis
     */
    public function logHandler($result )
    {
        $bak=$result;
        if ($result) {
            is_array($result) && $result = reset($result); //  by tmac
            $str = $result;
            if  ($str) {
                $data = json_decode($str, true);
                if(!$data){
                    echo 'json_err';
                    $this->paijuRedis->lpush('cardLogJsonErr', $bak);
                    return false;
                }
                $data['uids'] = json_encode($data['uids'], JSON_UNESCAPED_UNICODE);
                $data['detail'] = json_encode($data['detail'], JSON_UNESCAPED_UNICODE);

                //切磋场对局数据分类
                $data['isMatch']=$data['isMatch']?1:0;
                $data['reward']=isset($data['reward'])?$data['reward']:0;

                if(isset($data['clubID'])){
                    if($data['clubID']==108225){
                        echo '============'.$data['paiZuID'].'============';
                    }
                }
                //俱乐部对局数据分类 clubID,clubName
                $data['clubID']=isset($data['clubID'])?$data['clubID']:'';
                $data['clubName']=isset($data['clubName'])?$data['clubName']:'';


                //俱乐部对局数据玩法、房号清洗
                $data['clubConfigID']=isset($data['clubConfigID'])?$data['clubConfigID']:0;
                $data['hexWanFa']=isset($data['hexWanFa'])?$data['hexWanFa']:'';

                //$data['reward']=isset($data['reward'])?$data['reward']:0;
                $this->paijuRedis->multi();
                $result = $this->backup($data);
                if ($result) {
                    $result = true;//$this->backup2cahce($data);
                    if ($result) {
                        $result = $this->backup2db($data);
                        if ($result) {
                            $result = $this->backupUserPaizu($data);
                        }
                    }
                }
                if ($result) {
                    $this->paijuRedis->exec();
                    return true;
                } else {
                    $this->paijuRedis->discard();
                    return false;
                }
            }
        }
    }

    /**
     * 日志备份
     * @param $data
     */
    public function backup($data)
    {
        $dir = 'data/logs/paiju/';
        if ($error = $this->checkDir($dir)) {
            $this->e('日志目录不存在');
            return false;
        }

        if (isset($data['time']) && $data['time'] > 0) {

            $file = pathFormat($dir) . 'pjl_' . date('Ymd', $data['time']) . '.log';
            //---add by tmac 2016-12-15 (检查文件日志 是否超过允许最大值，超过则写入新的文件)
            if(is_file($file) && floor( self::LOG_FILE_SIZE <= filesize($file) ))
                rename($file,dirname($file).'/'.time().'-'.basename($file));
            //--end add
            $content = json_encode($data, JSON_UNESCAPED_UNICODE) . "\n";
            $result = $this->writeFile($file, $content, 'ab');
            if (!$result) {
                $this->e('日志备份写入文件失败', $data);
                return false;
            }
        } else {
            $this->e('时间戳不存在或为空', $data);
            return false;
        }

        return true;
    }

    /**
     * 写入牌局缓存库
     * @param $data
     */
    public function backup2cahce($data)
    {
        $key = self::CACHE_KEY . ':' . $data['paiZuID'] . $data['seq'];

        $result = $this->paijuRedis->hMset($key, $data);

        if (!$result) {
            $this->e('牌局日志缓存失败', $data);
            return false;
        }

        //设置过期时间
        $result = $this->paijuRedis->expire($key, $this->_expireTime);
        if (!$result) {
            $this->e('failed_redis_expire', array('key' => $key));
            return false;
        }

        return true;
    }

    /**
     * 写入牌局数据库
     * @param $data
     */
    public function backup2db($data)
    {
        $data['uids'] = json_decode($data['uids'], JSON_UNESCAPED_UNICODE);
        $data['detail'] = json_decode($data['detail'], JSON_UNESCAPED_UNICODE);

        $paijuLog = new PaijuLog();
        $paijuLog->isRedisLog(false);
        $paijuLog->setTableName();

        /**
         * 保存牌局
         */
        $juData = $paijuLog->savePaijuLog($data);
        /**
         * 保存牌组
         */
        //---add by tmac 2016-12-20 修复 返回错误bug
        $result = count( $juData ) < 1 ? [] : $paijuLog->savePaizuInfo($data, $juData);
        count( $result ) < 1  && $result =  false;
        //---end add
        //$result = $paijuLog->savePaizuInfo($data, $juData);  //注释 by tmac 2016-12-20

        return $result;
    }

    /**
     * 缓存用户的牌组ID
     * @param $data
     * @return bool
     */
    public function backupUserPaizu($data)
    {
        $data['uids'] = json_decode($data['uids'], JSON_UNESCAPED_UNICODE);
        // 房主退出牌局不玩牌时，也能查看牌局记录
        array_push($data['uids'], $data['creator']);

        if($data['clubID']){//录入俱乐部全部战绩
            $key_club = 'PZCLB:' . $data['clubID'];
            //删除俱乐部已存在的最新俱乐部牌局
            //$this->paijuRedis->lRem($key_club, $data['paiZuID']);
            //推入牌局
            $this->paijuRedis->lPush($key_club, $data['paiZuID']);
        }
        foreach (array_unique($data['uids']) as $uid) {
            if($uid == 0) continue;
            $key = 'UPZ:' . $uid;
            if($data['clubID']){//录入俱乐部个人战绩
                $key_club_uid = 'UPZCLB:' .$data['clubID'].'_'. $uid;
                //删除用户已存在的最新俱乐部牌局
                //$this->paijuRedis->lRem($key_club_uid, $data['paiZuID']);
                //推入牌局
                $this->paijuRedis->lPush($key_club_uid, $data['paiZuID']);
            }

            //删除已存在的最新牌局
            //$this->paijuRedis->lRem($key, $data['paiZuID']);
            //推入牌局
            $result = $this->paijuRedis->lPush($key, $data['paiZuID']);
            if (!$result) {
                $this->e('Redis Act Failed');
                return false;
            }
        }

        return true;
    }

}


/* function changeStr($str) {
    $reg = '/(\"nickName\\\":)([^}]*)}+?/';
    //preg_match_all($reg, $str, $match);
    $str = preg_replace_callback($reg,"back",$str);

    return $str;
}
function back($match) {
    $str = str_replace('\"', '', $match[2]);
    return $match[1].'\"'.base64_encode($str).'\"}';
}*/

?>

